package com.enation.app.javashop.consumer.shop.member;

import com.enation.app.javashop.consumer.core.event.MemberLoginEvent;
import com.enation.app.javashop.consumer.job.execute.EveryFiveMinExecute;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.client.member.MemberClient;
import com.enation.app.javashop.core.member.model.vo.MemberLoginMsg;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.statistics.model.dos.ShopPageView;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员登录后登录次数进行处理
 *
 * @author zh
 * @version v7.0
 * @date 18/4/12 下午5:38
 * @since v7.0
 */
@Service
public class MemberVisitConsumer implements EveryFiveMinExecute {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DaoSupport daoSupport;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public void everyFiveMin() {
        Integer today = Integer.valueOf(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        // 从Redis缓存中获取
        List<String> openIdList = getVisitOPenId();
        if (CollectionUtils.isEmpty(openIdList)) {
            return;
        }

        // 查询用户信息
        List<Integer> memberIds = getMemberByOpenId(openIdList);

        // 查询今日已访问用户(去重)
        List<Integer> memberIdsExist = getFirstVisitMember(today,  memberIds);
        if(!CollectionUtils.isEmpty(memberIdsExist)){
            memberIds.removeAll(memberIdsExist);
        }

        if (CollectionUtils.isEmpty(memberIds)) {
            return;
        }
        // 查询用户团长关系
        List<Map> memberDistributors = getMemberInfo( memberIds);

        // 新增访问
        batchInsert(today, memberDistributors);
    }

    private List<String> getVisitOPenId() {
        String key = CachePrefix.USER_VISIT.getPrefix();
        Long size = redisTemplate.opsForList().size(key);
        List<String> openIdList = new ArrayList<>();
        if(size>0){
            for (int i = 0; i < size; i++) {
                String openId = (String) redisTemplate.opsForList().leftPop(key);
                openIdList.add(openId);
            }
        }
        openIdList=openIdList.stream().distinct().collect(Collectors.toList());
        return openIdList;
    }

    private void batchInsert(Integer today, List<Map> memberDistributors) {
        String sql4 = "INSERT INTO `es_member_pv` (member_id,member_name,visit_day,visit_count,city,distributor_name,team_name,distributor_id,district) VALUES (?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.batchUpdate(sql4, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Map memberDistributor = memberDistributors.get(i);
                ps.setInt(1, (Integer) memberDistributor.get("member_id"));
                ps.setString(2, memberDistributor.get("nickname").toString());
                ps.setInt(3, today);
                ps.setInt(4, 1);
                if (memberDistributor.get("city") != null) {
                    ps.setString(5, memberDistributor.get("city").toString());
                } else {
                    ps.setNull(5, Types.VARCHAR);
                }
                if (memberDistributor.get("distributor_name") != null) {
                    ps.setString(6, memberDistributor.get("distributor_name").toString());
                } else {
                    ps.setNull(6, Types.VARCHAR);
                }
                if (memberDistributor.get("team_name") != null) {
                    ps.setString(7, memberDistributor.get("team_name").toString());
                } else {
                    ps.setNull(7, Types.VARCHAR);
                }
                if (memberDistributor.get("dis_member_id") != null) {
                    ps.setString(8, memberDistributor.get("dis_member_id").toString());
                } else {
                    ps.setNull(8, Types.INTEGER);
                }
                if (memberDistributor.get("district") != null) {
                    ps.setString(9, memberDistributor.get("district").toString());
                } else {
                    ps.setNull(9, Types.VARCHAR);
                }
            }

            @Override
            public int getBatchSize() {
                return memberDistributors.size();
            }

        });
    }

    private List<Map> getMemberInfo( List<Integer> memberIds) {
        Integer[] memberIdsArray2 = memberIds.toArray(new Integer[memberIds.size()]);
        List<Object> term3 = new ArrayList<>();
        String str3 = SqlUtil.getInSql(memberIdsArray2, term3);
        String sql3 = "SELECT mb.member_id,mb.nickname,mb.city,mb.county district ,db2.team_name,mb2.real_name distributor_name,db1.member_id_lv1 dis_member_id  FROM es_member mb " +
                "LEFT JOIN es_distribution db1 on mb.member_id = db1.member_id " +
                "LEFT JOIN es_distribution db2 on db1.member_id_lv1 = db2.member_id " +
                "LEFT JOIN es_member mb2 ON db1.member_id_lv1=mb2.member_id  where mb.member_id in (" + str3 + ")  ";
        return daoSupport.queryForList(sql3,  term3.toArray());
    }

    private List<Integer>  getFirstVisitMember(Integer today, List<Integer> memberIds) {
        Integer[] memberIdsArray1 = memberIds.toArray(new Integer[memberIds.size()]);
        List<Object> term2 = new ArrayList<>();
        String str2 = SqlUtil.getInSql(memberIdsArray1, term2);

        String sql2 = "select member_id from es_member_pv where visit_day ="+today+ " and member_id in (" + str2 + ") ";
        List<Map> list = daoSupport.queryForList(sql2, term2.toArray());
        return list.stream().map(map -> (Integer)map.get("member_id")).collect(Collectors.toList());
    }

    private List<Integer> getMemberByOpenId(List<String> openIdList) {
        String[] openIdArray = openIdList.toArray(new String[openIdList.size()]);
        List<Object> term1 = new ArrayList<>();
        String str1 = SqlUtil.getInSql(openIdArray, term1);

        String sql = "select member_id from es_connect where open_id in (" + str1 + ") ";
        List<Map> list = daoSupport.queryForList(sql, term1.toArray());
        return list.stream().map(map -> (Integer)map.get("member_id")).collect(Collectors.toList());
    }
}
